import axios, { AxiosInstance, AxiosError, AxiosResponse, InternalAxiosRequestConfig } from 'axios';
import {ElMessage} from "element-plus";
import router from "@/router";

const service: AxiosInstance = axios.create({
    timeout: 5000
});

service.interceptors.request.use(
    (config: InternalAxiosRequestConfig) => {
        // 从存储中获取 Token（如 localStorage、Vuex、Redux 等）
        const token = localStorage.getItem('token');
        // 如果 Token 存在，将其添加到请求头
        if (token) {
            config.headers.token = token;
        }
        return config;
    },
    (error: AxiosError) => {
        console.log(error);
        return Promise.reject();
    }
);

/**
 * 更改了一下接收到数据的响应格式
 */
service.interceptors.response.use(
    (response: AxiosResponse) => {
        const res = response.data;
        if (res.code >= 0) {
            return res;
        } else {
            if(res.code === -2){
                router.push('/login');
                ElMessage.error("身份信息已失效，请重新登陆")
            }
            ElMessage.error(res.msg || '操作失败');
            return Promise.reject(res.msg || 'error');
        }
    },
    (error: AxiosError) => {
        console.log(error);
        ElMessage.error('网络错误');
        return Promise.reject(error);
    }
);


export default service;
